const KPoint = require('../models/kPoint');
const {Op} = require('sequelize');
class KPointsCtl{
  //查看题型种类
  async find(ctx){
    const {count,rows} = await KPoint.findAndCountAll();
    ctx.body = {
      status:200,
      msg:'success',
      data:{
        count,
        data:rows
      }
    }
  }
  //增加题型
  async create(ctx){
    ctx.verifyParams({
      kp_name:{ type:'string', required:true }
    })
    //获取请求体中的题型名称
    const { kp_name } = ctx.request.body;
    //查重
    const repeatedKPoint = await KPoint.findOne({
      where:{
        kp_name:kp_name
      }
    });
    if(repeatedKPoint){
      ctx.throw(409,"已有此知识点");
    }
    const kPoint = await KPoint.create({
      kp_name:kp_name
    })
    ctx.body = kPoint;
  }
  //修改知识点
  async update(ctx){
    const kPoint = await KPoint.findOne({
      where:{
        kp_id:ctx.params.id
      }
    });
    if(!kPoint){ctx.throw(404,'当前知识点不存在');}
    const { kp_name } = ctx.request.body;
    const repeatedKPoint = await KPoint.findOne({
      where:{
        [Op.and]:[{
          kp_id:{
            [Op.ne]:ctx.params.id
          }
        },{
          kp_name:kp_name
        }]
      }
    })
    if(repeatedKPoint){ctx.throw(409,'已存在此知识点')}
     await KPoint.update({
      kp_name:kp_name
    },{
      where:{
        kp_id:ctx.params.id
      }
    })
    ctx.body = { kPoint:kp_name }
  }
  //删除知识点
  async delete(ctx){
    const kPoint = await KPoint.findOne({
      where:{
        kp_id:ctx.params.id
      }
    });
    if(!kPoint){ctx.throw(404,'知识点不存在');}
    await kPoint.destroy();
    ctx.status = 204
  }
}
module.exports = new KPointsCtl();